import { useState, useRef } from 'react'
import classNames from 'classnames'
import OSS from 'ali-oss'
import styled from 'styled-components'

const OssContainer = styled.div`
.choose-img {
display: block;
width: 150px;
height: 50px;
text-align: center;
line-height: 50px;
background-color: #42b983;
color: #fff;
border-radius: 5px;
cursor: pointer;
}
.tip {
color: #ccc;
}

    .img-container > li {
    	list-style: none;
    	width: 150px;
    	height: 100px;
    	float: left;
    	margin: 0 30px 30px 0;
    	border: 1px solid #ccc;
    }

    .upLoading {
    	background-color: #ccc;
    }

`

const ACCESSKEY = {
ID: '',
SECRET: ''
}

// 1. 添加 loading
// 2. 控制按钮点击状态

const client = new OSS({
region: 'oss-cn-beijing', // 地区 （阿里云 oss 申请的地区）
bucket: 'wyp0712', // 实例名称
accessKeyId: ACCESSKEY.ID, //
accessKeySecret: ACCESSKEY.SECRET
})
// imgList: [], // 存放上传完成的图片的列表
// isUploading: false // 当前图片是否正在上传

export const OssImage = () => {
	const [isUploading, setIsUploading] = useState(false)
	const [imgList, setImgList] = useState<any[]>([])
	const inputRef = useRef<any>()
	const classes = classNames('choose-img', {
		upLoading: isUploading
	})
	const onChange = (e: any) => {
		let target = e.target as HTMLInputElement
		// console.log('target:', target.files)
		// 可选链
		const newFiles = target.files
		console.log('newFiles:', newFiles)
		// 校验
		if (newFiles) {
			if (newFiles.length > 9) {
				alert('最多可以一次选择9张图片')
				return false
			}
			const files = []
			// for in
			// for of 循环什么？ 数据结构有什么特点？ {}
			// Symbol.iterator 迭代器
			for (const file of newFiles) {
				const size = file.size / 1024 / 1024 // 把单位转化成M
				if (size > 1) {
					alert('请选择1M以内的图片')
					return false
				}
				files.push(file)
			}

    		uploadFilesByOSS(files)
    	}
    }

    const uploadFilesByOSS = (files: any) => {
    	// this.isUploading = true
    	console.log('files:', files)
    	const uploadRequest = []
    	for (const file of files) {
    		uploadRequest.push(
    			new Promise((resolve, reject) => {
    				// 图片上传代码 http请求
    				client
    					.put(`${Math.random()}-${file.name}`, file)
    					.then((res) => {
    						console.log('oss返回结果：', res)
    						// this.imgList = [...this.imgList, res.url]
    						resolve(res.url)
    					})
    					.catch((err) => {
    						console.log(err)
    						reject(err)
    					})
    			})
    		)
    	}
    	console.log('uploadRequest:', uploadRequest)
    	// uploadRequest 一个包含所有promise实例的数组
    	// promise.all // promise.allSettled 区别？
    	// promise.all 处理什么？都成功返回成功
    	// promise.allSettled 可以检测到上传的成功或者失败的状态
    	Promise.allSettled(uploadRequest)
    		.then((res) => {
    			console.log('promise.allSettled:', res)
    			const imgs = []
    			// for of 是一个统一的遍历器接口
    			for (const item of res) {
    				if (item.status === 'fulfilled') {
    					imgs.push(item.value)
    				}
    			}
    			console.log('imgs:', imgs)
    			// this.imgList = imgs
    			// this.isUploading = false
    			setImgList([...imgs])
    		})
    		.catch((err) => {
    			console.log(err)
    		})
    }
    return (
    	<OssContainer className="oss-container">
    		<label htmlFor="upload" className={classes}>
    			选择图片上传
    		</label>
    		<input
    			type="file"
    			multiple
    			id="upload"
    			style={{ display: 'none' }}
    			accept="image/*"
    			onChange={onChange}
    			ref={inputRef}
    			disabled={isUploading}
    		/>
    		<p className="tip">
    			提示：一次可选择多张图片，最多不超过9张（单张图片大小 &lt; 1M）
    		</p>
    		<ul className="img-container">
    			{imgList.map((item, index) => {
    				return (
    					<li
    						key={index}
    						style={{ background: `url(${item}) no-repeat center/contain` }}
    					></li>
    				)
    			})}
    		</ul>
    	</OssContainer>
    )

}

export default OssImage
